package com.itheima.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.book.mapper.FavoriteMapper;
import com.itheima.book.pojo.entity.Favorite;
import com.itheima.book.service.FavoriteService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Override
    public boolean isFavorite(Long userId, Long bookId) {
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("book_id", bookId);
        return this.count(wrapper) > 0;
    }

    @Override
    @Transactional
    public void addFavorite(Long userId, Long bookId) {
        if (!isFavorite(userId, bookId)) {
            Favorite favorite = new Favorite();
            favorite.setUserId(userId);
            favorite.setBookId(bookId);
            favorite.setCreateTime(new java.util.Date());
            this.save(favorite);
        }
    }

    @Override
    @Transactional
    public void removeFavorite(Long userId, Long bookId) {
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("book_id", bookId);
        this.remove(wrapper);
    }
} 